package com.cloudbroker.bcs.platform.ltb.common.extservice.store.impl;

import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.ltb.common.extservice.store.StoreFields;
import com.cloudbroker.bcs.platform.ltb.common.extservice.store.StoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Map;


@Service(StoreFields.IMPL_TYPE_FILE)
public class FileStoreServiceImpl implements StoreService {
	
	private String FILE_PATH; 
	private static Logger logger = LoggerFactory.getLogger(FileStoreServiceImpl.class);

	public void initialize(Map<String, Object> params) {
		FILE_PATH = ValueUtil.getString(params.get(StoreFields.PROP_FILE_KEY_PREFIX + StoreFields.PROP_KEY_PATH));
		File file = new File(FILE_PATH);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	@Override
	public String uploadFile(String key, InputStream ips) throws Exception {
		return uploadFile(key, ips, true);
	}

	public String uploadFile(String key , byte[] b) throws Exception {
		return uploadFile(key , IOUtil.bytesToStream(b));
	}
	
	private String uploadFile(String key, InputStream in, boolean closeIn) throws Exception {
        String path = FILE_PATH+File.separator+key;

        OutputStream out = null;
        try {
        	out = new FileOutputStream(path);
        	int readedLen = -1;
            byte[] buff = new byte[4096];
            while (-1 != (readedLen = in.read(buff))) {
            	out.write(buff, 0, readedLen);
            }
            out.flush();
        }catch(Exception e) {
        	logger.error("上传文件出错", e);
        }
        finally {
        	IOUtil.close(out);
        	if (closeIn) {
        		IOUtil.close(in);
        	}
        }
        return key;
    }

	@Override
	public InputStream downloadFile(String key) {
		String path = FILE_PATH+File.separator+key;
		try {
			return new FileInputStream(path);
		} catch (Exception e) {
			logger.error("下载文件出错", e);
		}
		return null;
	}

	@Override
	public boolean deleteObject(String key) throws Exception {
		String path = FILE_PATH+File.separator+key;
		File file = new File(path);
		if( file.exists() ) {
			file.delete();
		}
		return true;
	}

}
